<template>
  <dt-modal-edit ref="editRef" title="编辑" @ok="onOk">
    <div class="flex">
      <label>角色包类型：</label>
      <div>{{ packName }}</div>
    </div>
    <div class="flex" style="margin-top: 20px">
      <label style="padding-top: 7px">功能权限编辑：</label>
      <div style="max-height: 500px; overflow: auto; flex: 1">
        <Tree
          :data="permissionData"
          ref="treeRef"
          show-checkbox
          check-strictly
          check-directly
          @on-check-change="treeChange"></Tree>
      </div>
    </div>
    <dt-loading ref="loadingRef" :loading="loading"></dt-loading>
  </dt-modal-edit>
</template>

<script setup>
  import { ref } from 'vue'
  import permissionMgr from '@/biz/permission'
  import apiMgr from '../biz/index'
  import dt from '@dt/dt'
  const emits = defineEmits(['search'])

  const [editRef, treeRef] = [ref(), ref()]
  const loading = ref(false)
  const permissionData = ref([])
  let [packName, id, authIds, checkAuthIds] = [ref(''), ref(''), ref(null), ref(null)]

  function show(data) {
    packName.value = data.title
    checkAuthIds.value = data.authIds || []
    id.value = data.id
    editRef.value.show()
    getSaWebAuthList()
  }
  function treeChange(val, target) {
    authIds.value = []
    dt.tool.treeChange(permissionData.value, target, treeRef.value).then((res) => {
      res.forEach((item) => {
        authIds.value.push(item.id)
      })
    })
  }
  function getSaWebAuthList() {
    // 权限树数据
    loading.value = true
    permissionMgr
      .saWebAuthList()
      .then((res) => {
        permissionData.value = res
        resolveTree(permissionData.value, checkAuthIds.value)
        loading.value = false
      })
      .catch((err) => {
        loading.value = false
      })
  }
  function resolveTree(treeData, ids) {
    treeData.forEach((item) => {
      if (ids.includes(Number(item.id))) {
        item.checked = true
      } else {
        item.checked = false
      }
      if (item.children && item.children.length > 0) {
        resolveTree(item.children, ids)
      }
    })
  }
  function onOk(data) {
    let params = {
      id: id.value,
      authIds: authIds.value
    }
    apiMgr.saRoleTypeSave(params).then((res) => {
      dt.ui.Message.success('保存成功')
      emits('search')
      editRef.value.hide()
    })
  }

  defineExpose({ show })
</script>

<style scoped></style>
